//
//  XYTUploadInfoViewController.m
//  XYTPayOrderSystem
//
//  Created by wupeng on 2017/8/30.
//  Copyright © 2017年 wupeng. All rights reserved.
//

#import "XYTUploadInfoViewController.h"
#import "XYTUserInfoUploadCell.h"
#import "XYTUploadLicenseCell.h"
@interface XYTUploadInfoViewController ()<UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,XYTUploadLicenseCellDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) NSMutableDictionary *params;

@property (nonatomic, strong) NSData *imageData;

@end

@implementation XYTUploadInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"用户信息";
    self.edgesForExtendedLayout=UIRectEdgeNone;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setupUI];
    
    [self addNotification];
}

#pragma mark - aboutUI
- (void)setupUI{
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 10, kScreen_Width , kScreen_Height-10) style:UITableViewStylePlain];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.dataSource = self;
    tableView.delegate = self;
    [self.view addSubview:tableView];
    self.tableView = tableView;
}
- (void)addNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(upMoveScrollerView:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downMoveScrollerView:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateParams:) name:@"UserInfoUploadCell_textField" object:nil];
}

- (void)upMoveScrollerView:(NSNotification *)notification{
    CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat ty = rect.size.height;
    self.tableView.contentOffset = CGPointMake(0, ty);
    
}

- (void)downMoveScrollerView:(NSNotification *)notification{
    self.tableView.contentOffset = CGPointMake(0, 0);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
#pragma mark - private Methods
- (void)updateParams:(NSNotification *)notification{
    NSDictionary *param = notification.userInfo;
    for (NSString *key in param) {
        [self.params xyt_setObj:param[key] forKey:key];
    }
}

- (void)sendUserInfo{
    //一定要先结束编辑，将cell中textfiled里的text通知发过来，
    [self.view endEditing:YES];
    //设置请求头参数
    NSDictionary *params = [self setupRequestHeader];
    [UIView showHUD:nil];
    [XYTNetRequest uploadImage:self.imageData POST:UploadUserInfoUrl parameters:params isNeedKey:NO success:^(id responseObject) {
        [UIView hideHUD];
        [UIView showCustomToast:@"用户信息上传成功"];
        [self.navigationController popViewControllerAnimated:YES];
        
    } failure:^(NSString *errorMsg) {
        [UIView hideHUD];
        [self showAlertWithTitle:errorMsg];
    }];
    
}

- (NSDictionary *)setupRequestHeader{
    NSInteger userId = [XYTUserInfoManager sharedManager].userId;
    NSInteger userType = [XYTUserInfoManager sharedManager].roleType;
    NSString *userIdStr = [NSString stringWithFormat:@"%ld",(long)userId];
    NSString *userTypeStr = [NSString stringWithFormat:@"%ld",(long)userType];
    NSString *sign = [NSString stringWithFormat:@"%@%@%@%@%@%@%@%@%@%@%@",AppKey,AppSecret,userIdStr,userTypeStr,self.params[@"网点名称*"],self.params[@"联系人*"],self.params[@"联系人电话*"],self.params[@"银行开户人*"],self.params[@"银行开户网点*"],self.params[@"银行卡号*"],self.params[@"推荐业务员"]];
    NSString *signMd5 = [Md5Util md5:sign];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params xyt_setObj:@(userId) forKey:@"userId"];
    [params xyt_setObj:@(userType) forKey:@"userType"];
    [params xyt_setObj:self.params[@"网点名称*"] forKey:@"siteName"];
    [params xyt_setObj:self.params[@"联系人*"] forKey:@"contactName"];
    [params xyt_setObj:self.params[@"联系人电话*"] forKey:@"contactPhone"];
    [params xyt_setObj:self.params[@"银行开户人*"] forKey:@"bankPerson"];
    [params xyt_setObj:self.params[@"银行开户网点*"] forKey:@"bankSite"];
    [params xyt_setObj:self.params[@"银行卡号*"] forKey:@"bankCardNo"];
    [params xyt_setObj:self.params[@"推荐业务员"] forKey:@"recommendPersopn"];
    [params xyt_setObj:signMd5 forKey:@"sign"];
    return params;
}

#pragma mark - XYTUploadLicenseCellDelegate
- (void)onClickChooseFile{
    [self.view endEditing:YES];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        //调用系统相册的类
        UIImagePickerController *pickerController = [[UIImagePickerController alloc]init];
        pickerController.allowsEditing = NO;
        pickerController.sourceType =  UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        pickerController.delegate = self;
        [self presentViewController:pickerController animated:YES completion:^{
            
        }];
    }
}

#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //获取图片的url    UIImagePickerControllerReferenceURL
    NSURL* url = [info objectForKey:UIImagePickerControllerReferenceURL];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.imageData = UIImageJPEGRepresentation(image, 1);//JPG图片转二进制数据并压缩
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    NSMutableDictionary *imageDic = [NSMutableDictionary dictionaryWithCapacity:2];
    [imageDic xyt_setObj:url forKey:@"imageUrl"];
    [imageDic xyt_setObj:self.imageData forKey:@"imageData"];
    //刷新UI
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"licenseImgChooseFinished" object:nil userInfo:imageDic];
        [self.tableView reloadData];
    });
}

//点击取消按钮所执行的方法
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark - tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger rowNum = indexPath.row;
    if (rowNum == 3) {
        static NSString *licenseCellId = @"XYTUploadLicenseCell";
        XYTUploadLicenseCell *cell = [tableView dequeueReusableCellWithIdentifier:licenseCellId];
        if (!cell) {
            cell = [[XYTUploadLicenseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:licenseCellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setStarTitle:[self.dataSource[rowNum] objectForKey:@"title"]];
            cell.delegate = self;
        }
        return cell;
    }else{
        static NSString *userInfoCellId = @"XYTUserInfoUploadCell";
        XYTUserInfoUploadCell *cell = [tableView dequeueReusableCellWithIdentifier:userInfoCellId];
        if (!cell) {
            cell = [[XYTUserInfoUploadCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:userInfoCellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setStarTitle:[self.dataSource[rowNum] objectForKey:@"title"]];
            cell.textField.placeholder = [self.dataSource[rowNum] objectForKey:@"placeholder"];
        }
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 3) {
        return 156.0f;
    }
    return 40.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 60.0f;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 60)];
    UIButton *confirmBtn = [[UIButton alloc] initWithFrame:CGRectMake((kScreen_Width-120)*0.5, 10, 150, 35)];
    confirmBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    confirmBtn.backgroundColor = [UIColor redColor];
    [confirmBtn addTarget:self action:@selector(sendUserInfo) forControlEvents:UIControlEventTouchUpInside];
    [confirmBtn.layer setCornerRadius:2.0];
    [confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    [footView addSubview:confirmBtn];
    return footView;
}

#pragma mark - setter/getter
-(NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithObjects:@{@"title":@"网点名称*",@"placeholder":@"请输入网点名称"},@{@"title":@"联系人*",@"placeholder":@"请输入网点联系人"},@{@"title":@"联系人电话*",@"placeholder":@"请输入网点联系人电话"},@{@"title":@"营业执照"},@{@"title":@"银行开户人*",@"placeholder":@"请输入银行联系人"},@{@"title":@"银行开户网点*",@"placeholder":@"请输入银行开户网点"},@{@"title":@"银行卡号*",@"placeholder":@"请输入银行卡号"},@{@"title":@"推荐业务员",@"placeholder":@"请输入推荐业务员"}, nil];
    }
    return _dataSource;
}

-(NSMutableDictionary *)params{
    if (!_params) {
        _params = [NSMutableDictionary dictionary];
    }
    return _params;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
